package eolica

import br.leiam.eolica.facade.FacadeEolica;

class UserController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	
	def afterInterceptor = { model, modelAndView ->
		try{
			if (session["isMobile"]) {
				modelAndView.viewName = modelAndView.viewName + "_m"
			 }
		}catch(NullPointerException e){
		
		}
		
	}
	
	
	def login = { LoginCommand cmd ->
		if(request.method == 'POST') {
			if(!cmd.hasErrors()) {
				if(cmd.getUser()){				
					session.user = cmd.getUser()
					if (session["isMobile"]) {
						forward(controller: "eolica", action: "index")
					}else{
						render(view:'/index')
					}
				} else {
					flash.message = "Login ou senha invalida"
					render(view:'/index')
				}
			}
			else {
				render(view:'/index', model:[loginCmd:cmd])
			}
		}
		else {
			render(view:'/index')
		}
	}
	
	def goIndex = {
		
		
	}
	
	def logoff = { 
		//throw new Exception("Teste")
		//def isMobile = request['isMobile']
		session.user = null
		/*if (isMobile) 
			render(view:'/index_m')
		else*/
			render(view:'/index')
	}
	
	
	
	

    def gerenciar = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [userInstanceList: User.list(params), userInstanceTotal: User.count()]
    }

    def create = {
        def userInstance = new User()
        userInstance.properties = params
        return [userInstance: userInstance]
    }

    def save = {
        def userInstance = new User(params)
        if (userInstance.save(flush: true)) {
            flash.message = "Usuario criado com Sucesso"
            redirect(action: "show", id: userInstance.id)
        }
        else {
            render(view: "create", model: [userInstance: userInstance])
        }
    }

    def show = {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = "Usuario nao encontrado"
            redirect(action: "list")
        }
        else {
            [userInstance: userInstance]
        }
    }

    def edit = {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message =  "Usuario nao encontrado"
            redirect(action: "list")
        }
        else {
            return [userInstance: userInstance]
        }
    }

    def update = {
        def userInstance = User.get(params.id)
        if (userInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (userInstance.version > version) {
                    userInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'user.label', default: 'User')] as Object[], "Outro usuario atualizou os valores deste objeto enquanto voce estava editando")
                    render(view: "edit", model: [userInstance: userInstance])
                    return
                }
            }
            userInstance.properties = params
            if (!userInstance.hasErrors() && userInstance.save(flush: true)) {
                flash.message = "Usuario editado com sucesso"
                redirect(action: "show", id: userInstance.id)
            }
            else {
                render(view: "edit", model: [userInstance: userInstance])
            }
        }
        else {
            flash.message = "Usuario nao encontrado"
            redirect(action: "list")
        }
    }

    def delete = {
        def userInstance = User.get(params.id)
        if (userInstance) {
            try {
                userInstance.delete(flush: true)
                flash.message = "Usuario deletado com sucesso"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Nao foi possivel deletar o Usuario"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message =  "Usuario nao encontrado"
            redirect(action: "list")
        }
    }
}
